#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据验证工具
"""

import re
from typing import Dict, Any


def validate_email(email: str) -> bool:
    """验证邮箱格式"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None


def validate_username(username: str) -> bool:
    """验证用户名格式"""
    if not username or len(username) < 3 or len(username) > 20:
        return False
    # 只允许字母、数字和下划线
    pattern = r'^[a-zA-Z0-9_]+$'
    return re.match(pattern, username) is not None


def validate_password(password: str) -> bool:
    """验证密码强度"""
    if not password or len(password) < 6:
        return False
    return True


def validate_login_data(data: Dict[str, Any]) -> Dict[str, Any]:
    """验证登录数据"""
    if not data:
        return {'valid': False, 'message': 'No data provided'}
    
    username = data.get('username')
    password = data.get('password')
    
    if not username:
        return {'valid': False, 'message': 'Username is required'}
    
    if not password:
        return {'valid': False, 'message': 'Password is required'}
    
    if not validate_username(username):
        return {'valid': False, 'message': 'Invalid username format'}
    
    return {'valid': True, 'message': 'Valid login data'}


def validate_register_data(data: Dict[str, Any]) -> Dict[str, Any]:
    """验证注册数据"""
    if not data:
        return {'valid': False, 'message': 'No data provided'}
    
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    
    if not username:
        return {'valid': False, 'message': 'Username is required'}
    
    if not password:
        return {'valid': False, 'message': 'Password is required'}
    
    if not validate_username(username):
        return {'valid': False, 'message': 'Username must be 3-20 characters, letters, numbers and underscore only'}
    
    if not validate_password(password):
        return {'valid': False, 'message': 'Password must be at least 6 characters'}
    
    if email and not validate_email(email):
        return {'valid': False, 'message': 'Invalid email format'}
    
    return {'valid': True, 'message': 'Valid registration data'}


def validate_project_data(data: Dict[str, Any]) -> Dict[str, Any]:
    """验证项目数据"""
    if not data:
        return {'valid': False, 'message': 'No data provided'}
    
    name = data.get('name')
    created_by = data.get('created_by')
    
    if not name:
        return {'valid': False, 'message': 'Project name is required'}
    
    if not created_by:
        return {'valid': False, 'message': 'Creator is required'}
    
    if len(name) < 2 or len(name) > 100:
        return {'valid': False, 'message': 'Project name must be 2-100 characters'}
    
    return {'valid': True, 'message': 'Valid project data'}